﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Reflection;
using System.Drawing;
using DailyPhoto.Common;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Bson.Serialization;
using Newtonsoft.Json;

namespace DailyPhoto.Entities
{
    public class FileSystemRepository : IRepository
    {

        private Faces.FaceDetector detector;

        public FileSystemRepository()
        {
            detector = new Faces.FaceDetector("C:\\OpenCV\\haarcascade_frontalface_alt.xml");
        }

        public IEnumerable<Photo> Fetch()
        {
            var lstFiles = new List<FileInfo>();

            foreach (var dir in Application.Config.directories)
            {
                lstFiles.AddRange(Util.ListAllFiles(new DirectoryInfo(dir.ToString())));
            }


            var photos = lstFiles
            .Where(x =>
            {
                var ext = Path.GetExtension(x.FullName);
                return string.Equals(ext, ".jpeg", StringComparison.CurrentCultureIgnoreCase) ||
                       string.Equals(ext, ".jpg", StringComparison.CurrentCultureIgnoreCase);
            })
            .Select(x => 
            {
                var p = new FSPhoto(x.FullName);
                p.RepositoryName = this.Name;
                return p;
            })
            .Where(y =>
            {
                return !(new BlackList().GetEntriesOfRepository(this.Name).Select(z => z.PhotoId).Contains(y.PhotoId));
            })
            .ToArray();


            var db = Database.GetCollection<FSPhoto>("fsphotos");

            foreach (var p in photos)
            {
                var r = db.Find(Query.EQ("OriginalPath", p.OriginalPath)).FirstOrDefault();

                if (r != null)
                {
                    p.Faces = r.Faces;
                    continue;
                }

                Bitmap bmp;
                bmp = new Bitmap(p.OriginalPath);

                int maxWidth = 750;
                if (bmp.Width > maxWidth)
                {
                    Bitmap newBmp = new Bitmap(bmp, maxWidth, (int)(((float)maxWidth / (float)bmp.Width) * (float)bmp.Height));
                    bmp.Dispose();
                    bmp = newBmp;
                }

                p.Faces = detector.FindFaces(bmp);

                db.Insert(p);
            }

            return photos.Where(x => x.Faces.Count() >= 2).ToArray();
        }

        public string Name
        {
            get { return "FileSystem"; }
        }
    }

}
